package org.jeecg.glr.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.glr.entity.*;
import org.jeecg.glr.service.*;
import org.jeecg.glr.util.GLRConstant;
import org.jeecg.glr.util.StringUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 路灯灯杆管理
 * @Author: jeecg-boot
 * @Date: 2020-03-05
 * @Version: V1.0
 */
@RestController
@RequestMapping("/glr/glrLightPole")
@Slf4j
public class GlrLightPoleController extends JeecgController<GlrLightPole, IGlrLightPoleService> {
    @Autowired
    private IGlrLightPoleService glrLightPoleService;
    @Autowired
    private IGlrLightPoleDeviceService glrLightPoleDeviceService;
    @Autowired
    private IGlrProjectService glrProjectService;
    @Autowired
    private IGlrVideoService glrVideoService;
    @Autowired
    private IGlrRadioService glrRadioService;
    @Autowired
    private IGlrLedService glrLedService;
    @Autowired
    private IGlrLightService glrLightService;
    @Autowired
    private IGlrGatewayService glrGatewayService;
    @Autowired
    private IGlrSensorService glrSensorService;

    @Resource IGlrRadioServerService glrRadioServerService;

    @Autowired
    private IGlrVideoYsService glrVideoYsService;

    @Resource
    ILedCommon ledCommon;

    /**
     * 分页列表查询
     *
     * @param glrLightPole
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<?> queryPageList(GlrLightPole glrLightPole,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        QueryWrapper<GlrLightPole> queryWrapper = QueryGenerator.initQueryWrapperCode(glrLightPole, req.getParameterMap());
        Page<GlrLightPole> page = new Page<GlrLightPole>(pageNo, pageSize);
        IPage<GlrLightPole> pageList = glrLightPoleService.page(page, queryWrapper);
        List<GlrLightPole> list = pageList.getRecords();
        for (GlrLightPole glr :
                list) {
            if (StringUtil.isNotEmpty(glr.getProjectCode())) {
                glr.setProjectName(glrProjectService.getGlrProjectByCode(glr.getProjectCode()).getName());
            }
        }
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param glrLightPole
     * @return
     */
    @AutoLog(value = "添加灯杆",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody GlrLightPole glrLightPole) {
        glrLightPoleService.saveAndSynchronizationGateWay(glrLightPole);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param glrLightPole
     * @return
     */
    @AutoLog(value = "修改灯杆",logType= CommonConstant.LOG_TYPE_2)
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody GlrLightPole glrLightPole) {
        glrLightPoleService.updateAndSynchronizationGateWayById(glrLightPole);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "删除灯杆",logType= CommonConstant.LOG_TYPE_2)
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try{
            glrLightPoleService.deleteById(id);
        }catch (Exception ex){
            return Result.error(ex.getMessage());
        }
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "删除灯杆",logType= CommonConstant.LOG_TYPE_2)
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        try{
            glrLightPoleService.deleteBatchByIds(Arrays.asList(ids.split(",")));
        }catch (Exception ex){
            return Result.error(ex.getMessage());
        }
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        GlrLightPole glrLightPole = glrLightPoleService.getById(id);
        if (glrLightPole == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(glrLightPole);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param glrLightPole
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, GlrLightPole glrLightPole) {
        return super.exportXls(request, glrLightPole, GlrLightPole.class, "路灯管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<GlrLightPole> list = ExcelImportUtil.importExcel(file.getInputStream(), GlrLightPole.class, params);
                //update-begin-author:taoyan date:20190528 for:批量插入数据
                long start = System.currentTimeMillis();
                glrLightPoleService.saveBatch(list);
                //400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
                //1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
                log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
                //update-end-author:taoyan date:20190528 for:批量插入数据
                return Result.ok("文件导入成功！数据行数：" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    /**
     * 修改经纬度
     *
     * @param
     * @return
     */
    @AutoLog(value = "修改灯杆经纬度",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/updateLg")
    public Result<?> updateLg(@RequestBody GlrLightPole glrLightPole) {
        glrLightPoleService.updateById(glrLightPole);
        return Result.ok("经纬度修改成功");
    }

    @AutoLog(value = "修改项目所有灯杆经纬度",logType= CommonConstant.LOG_TYPE_2)
    @PostMapping(value = "/updateLgAll")
    public Result<?> updateLgAll(@RequestBody GlrLightPole glrLightPole) {
        glrLightPoleService.updateLgAll(glrLightPole);
        return Result.ok("此项目所有灯杆经纬度修改成功");
    }



    /**
     * 通过id查询
     *
     * @param
     * @return
     */
    @PostMapping(value = "/getLightPoleList")
    public Result<?> getLightPoleList(@RequestBody GlrLightPole glrLightPole) {
        QueryWrapper queryWrapper = QueryGenerator.initQueryWrapperCode();
        if (glrLightPole != null) {
            if (StringUtil.isNotEmpty(glrLightPole.getProjectCode())) {
                queryWrapper.eq("project_code", glrLightPole.getProjectCode());
            }
        }
        if (GLRConstant.YN_N.equals(glrLightPole.getIsWisdom())) {
            queryWrapper.eq("light_pole_type", GLRConstant.GLR_LIGHT_POLE_TYPE_1);
        }
        if (GLRConstant.YN_Y.equals(glrLightPole.getIsWisdom())) {
            Object[] LIGHT_POLE_TYPE ={GLRConstant.GLR_LIGHT_POLE_TYPE_2,GLRConstant.GLR_LIGHT_POLE_TYPE_3};
            queryWrapper.in("light_pole_type",LIGHT_POLE_TYPE);
        }
        queryWrapper.orderByAsc("code");

        List<GlrLightPole> list = glrLightPoleService.list(queryWrapper);

        queryWrapper = QueryGenerator.initQueryWrapperCode();
        if (glrLightPole != null) {
            if (StringUtil.isNotEmpty(glrLightPole.getProjectCode())) {
                queryWrapper.eq("code", glrLightPole.getProjectCode());
            }
        }
        List<GlrProject> listProject = glrProjectService.list(queryWrapper);

        for (GlrLightPole domain : list) {
            String stname = "";
            if (StringUtil.isNotEmpty(domain.getProjectCode())) {
                if (listProject.size() > 0) {
                    for (GlrProject project : listProject) {
                        if (domain.getProjectCode().equals(project.getCode())) {
                            stname = stname + "" + project.getName() + "-";
                            break;
                        }
                    }
                }
            }
            stname = stname + domain.getCode() + "灯杆";
            domain.setName(stname);
        }
        return Result.ok(list);
    }



    /**
     * 通过id查询
     *
     * @param
     * @return
     */
    @PostMapping(value = "/getLightPoleDevice")
    public Result<?> getLightPoleDevice(@RequestBody GlrLightPole pl) throws Exception {
        Map<String,Object> map = new HashMap<>();
        GlrLightPole glrLightPole = glrLightPoleService.getById(pl.getId());
        List<GlrLightPoleDevice> list = glrLightPoleDeviceService.glrLightPoleDeviceListById(glrLightPole.getCode(), glrLightPole.getProjectCode());
        List<GlrRadio> radioList = new ArrayList<>();
        List<GlrLed> ledList = new ArrayList<>();
        List<GlrLight> lightList = new ArrayList<>();
        List<GlrGateway> gateWayList = new ArrayList<>();
        List<GlrSensor> sensorWayList = new ArrayList<>();
        List<GlrVideo> videoList = new ArrayList<>();
        GlrProject glrProject=glrProjectService.getGlrProjectByCode(glrLightPole.getProjectCode());;
        for (GlrLightPoleDevice device :
                list) {
            if (GLRConstant.GLR_LIGHT_POLE_DEVICE_01.equals(device.getDeviceType())) {
                //   glrLightPoleDeviceService.getRadioByPoleCodeAndProjectCode(glrLightPole.getCode(), glrLightPole.getProjectCode());
                GlrRadio radio = glrRadioService.getById(device.getDeviceId());
                glrRadioServerService.updateGlrRadioStatus(radio,null,null);
                radioList.add(radio);
                // device.setDevice01Radio(radio);
            }
            if (GLRConstant.GLR_LIGHT_POLE_DEVICE_02.equals(device.getDeviceType())) {
                GlrLed glrLed = glrLedService.getById(device.getDeviceId());
                if(StringUtil.isNotEmpty(glrLed.getStatus())&&GLRConstant.YN_Y.equals(glrLed.getStatus())){
                    String  imgbase64=ledCommon.getLedImgByCode(glrLed.getCode());
                    glrLed.setCodes("data:image/png;base64,"+imgbase64);
                }
                ledList.add(glrLed);
                // device.setDevice02Led(glrLed);
            }
            if (GLRConstant.GLR_LIGHT_POLE_DEVICE_03.equals(device.getDeviceType())) {
                GlrLight glrLight = glrLightService.getById(device.getDeviceId());
                lightList.add(glrLight);
                // device.setDevice03Light(glrLight);
            }
            if (GLRConstant.GLR_LIGHT_POLE_DEVICE_04.equals(device.getDeviceType())) {
                GlrGateway glrGateway = glrGatewayService.getById(device.getDeviceId());
                gateWayList.add(glrGateway);
                // device.setDevice04Gateway(glrGateway);
            }
            if (GLRConstant.GLR_LIGHT_POLE_DEVICE_05.equals(device.getDeviceType())) {
                GlrSensor deviceDomain = glrSensorService.getById(device.getDeviceId());
                GlrSensorData data=  glrSensorService.getGlrSensorByCodeOne(deviceDomain.getCode());
                deviceDomain.setGlrSensorData(data);
                sensorWayList.add(deviceDomain);
                //  device.setDevice05Sensor(deviceDomain);
            }
            if (GLRConstant.GLR_LIGHT_POLE_DEVICE_06.equals(device.getDeviceType())) {
                GlrVideo vide = glrVideoService.getById(device.getDeviceId());
                if(StringUtil.isNotEmpty(vide.getEquipmentUrl())){
                    JSONObject json= JSON.parseObject(vide.getEquipmentUrl());
                    String url=json.getString("rtmp");
                    vide.setEquipmentUrl(url);
                    GlrVideoYs glrVideoYs=glrVideoYsService.getGlrVideoYsByCode(vide.getVideoYsCode());
                    String stToken = glrVideoYsService.getToken(glrVideoYs);
                   String status= glrVideoYsService.getStatus(vide,stToken);
                   vide.setEquipmentStatus(status);
                }
                videoList.add(vide);
            }
        }
        map.put("glrLightPole",glrLightPole);
        map.put("radioList",radioList);
        map.put("videoList",videoList);
        map.put("sensorWayList",sensorWayList);
        map.put("gateWayList",gateWayList);
        map.put("lightList",lightList);
        map.put("ledList",ledList);
        map.put("radioList",radioList);
        map.put("glrProject",glrProject);
        return Result.ok(map);
    }




}
